package com.woniuxy.rms.config;

import com.woniuxy.rms.util.DataResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Auther: ChenGang  <br/>
 * Date: 2020/3/27 0027:下午 2:22  <br/>
 * Description:文件上传
 */
@Component
public class UploadConfig {

    public DataResult uploadImg(MultipartFile file, String loadPath, String imgPath) {
        //获取文件名称
        String fileName = file.getOriginalFilename();
        String last = fileName.substring(fileName.lastIndexOf('.'));
        //文件名称
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String fileDir = simpleDateFormat.format(new Date());
        //获取唯一id
        String uuid = UUID.randomUUID().toString().trim().replace("-", "");
        //文件名
        fileName = uuid + fileDir + last;
        //文件全路径
        String path = loadPath + imgPath + File.separator + fileName;
        //归档
        try {
            //判断该文件夹是否存在
            File file1 = new File(path);
            if(!file1.exists()){
                file1.mkdirs();
            }
            file.transferTo(file1);
            Map map = new HashMap();
            map.put("src", imgPath + File.separator + fileName);
            return DataResult.success(map);
        } catch (IOException e) {
            e.printStackTrace();
            return DataResult.failed("上传失败！");
        }
    }
}